/*
 * @Author: intellectual-seeker 3336339701@qq.com
 * @Date: 2025-08-07 21:39:04
 * @LastEditors: intellectual-seeker 3336339701@qq.com
 * @LastEditTime: 2025-08-07 23:05:48
 * @FilePath: /code/lesson25/test3/task.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
using namespace std;
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>

typedef void(* task_t)(pid_t, int);
typedef void(* work_t)(int);

//模拟任务：打印读端文件描述符
//链接数据库
void ConnectMysql(pid_t subprocess_id, int fd)
{
    cout << "subprocess_id: " << subprocess_id << " fd: " << fd << " task is connect mysql\n" << endl;
}

//加载配置信息
void ReloadConf(pid_t subprocess_id, int fd)
{
    cout << "subprocess_id: " << subprocess_id << "fd: " << fd << " task is reload conf\n" << endl;
}

//打印日志
void PrintLog(pid_t subprocess_id, int fd)
{
    cout << "subprocess_id: " << subprocess_id << "fd: " << fd << " task is print log\n" << endl;
}

task_t task[3] = {ConnectMysql, ReloadConf, PrintLog};

size_t NextTask()
{
    return rand() % 3;
}

void worker(int fd)
{
    while(true)
    {
        //从文件描述符0处，读取任务码
        size_t commandcode;//任务不小于0
        int n = read(0, &commandcode, sizeof(commandcode));

        if(n < 0)
        {
            cout << "read ret: " << n << " errno: " << strerror(errno) << endl;
        }

        if(n == sizeof(commandcode))
        {
            if(commandcode >= 3) continue;//任务码不合法
            task[commandcode](getpid(), fd);
        }
        else if(n == 0)
            break;
    }
}